package com.benson.thread.interrupt;

import java.math.BigInteger;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class PrimeProducer extends Thread{

	private final BlockingQueue<BigInteger> queue;
	
	PrimeProducer(BlockingQueue<BigInteger> queue){
		this.queue = queue;
	}

	@Override
	public void run() {
		BigInteger p = BigInteger.ONE;
		try {
			while(!Thread.currentThread().isInterrupted()){
				
					queue.put(p = p.nextProbablePrime());
				
			}
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		
	}
	
	public void cancel(){
		interrupt();
	}
	
	public static void main(String[] args) {
		System.out.println(BigInteger.ONE);
	}
	
	private static ExecutorService taskExec = Executors.newCachedThreadPool();
	public static void timedRun(Runnable r, long timeout, TimeUnit unit ) throws InterruptedException{
		Future<?> task = taskExec.submit(r);
		
		
			try {
				task.get(timeout, unit);
			} catch (ExecutionException e) {
//				throw e.getCause();
			} catch (TimeoutException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			finally{
				task.cancel(true);
			}
		
	}
}
